package org.eden.web.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.eden.rpc.common.entity.dao.User;

import java.util.Calendar;

public class JWTUtil {

    private static final String jwtSecret = "zachery";

    public static String createToken(User user){
        Calendar instance = Calendar.getInstance();
        int expiredTime = 60 * 60 * 24; // 10min过期, 单位s
        instance.add(Calendar.SECOND, expiredTime);
        return JWT.create()
                //头可以不指定一般用默认值
                .withClaim("username", user.getUsername())//payLoad
                .withClaim("userId", user.getId())
                .withClaim("authority", user.getAuthority())
                .withExpiresAt(instance.getTime()) //指定令牌的过期时间
                .sign(Algorithm.HMAC256(JWTUtil.jwtSecret));
    }

    public static User verifyToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWTUtil.jwtSecret)).build();
        try {
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            User user = new User();
            user.setAuthority(decodedJWT.getClaim("authority").asString());
            user.setId(decodedJWT.getClaim("userId").asLong());
            user.setUsername(decodedJWT.getClaim("username").asString());
            return user;
        }catch (JWTVerificationException e){
            return null;
        }
    }
}
